package com.opensource.afuluo.ctx;

import com.google.common.base.Joiner;
import com.opensource.afuluo.enums.ProcessStatus;

import java.util.HashMap;
import java.util.Map;

public class CommonContext implements Context {

    private Map<String, Object> configurations = new HashMap<>();

    private String msg;

    private boolean error;

    private boolean react;

    private boolean interrupted;

    private Context parent;

    @Override
    public String getUnique() {
        return null;
    }

    @Override
    public <T> T getConfig(Class<T> clazz) {
        return getConfig(clazz, "");
    }

    @Override
    public <T> T getConfig(Class<T> clazz, String config) {
        Object obj = configurations.get(Joiner.on("#").join(clazz.getCanonicalName(), config));
        if (null != obj && obj.getClass().isAssignableFrom(clazz)) {
            return clazz.cast(obj);
        }
        return null;
    }

    @Override
    public <T> T getConfigIfPresent(Class<T> clazz, String config) throws IllegalArgumentException {
        return null;
    }

    @Override
    public <T> void setConfig(Class<T> clazz, Object obj) {
        setConfig(clazz, "", obj);
    }

    @Override
    public <T> void setConfig(Class<T> clazz, String config, Object obj) {
        configurations.put(Joiner.on("#").join(clazz.getCanonicalName(), config), obj);
    }

    @Override
    public <T> void setConfigIfAbsent(Class<T> clazz, String config, Object obj) throws IllegalArgumentException {

    }

    @Override
    public boolean hasError() {
        return error;
    }

    @Override
    public boolean isSuccess() {
        return !error;
    }

    @Override
    public boolean isInterrupted() {
        return interrupted;
    }

    @Override
    public boolean isReact() {
        return react;
    }

    @Override
    public String getError() {
        return msg;
    }

    @Override
    public void setStatus(ProcessStatus status, String msg) {

    }

    @Override
    public void markReact(boolean react) {
        this.react = react;
    }

    @Override
    public Context fork() {
        Context ctx = new CommonContext();
        ctx.setParent(this);
        return ctx;
    }

    @Override
    public Context getParent() {
        return parent;
    }

    @Override
    public void setParent(Context ctx) {
        this.parent = ctx;
    }
}
